import React, { useContext, useState } from "react";
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  FlatList,
  Alert,
} from "react-native";
import { AntDesign } from "@expo/vector-icons";
import ArticleCard from "../../components/preAdmin/ArticleCard";
import ArticleContext from "../../context/preparation/ArticleContext";
import NoData from "../../components/preAdmin/NoData";
import LoadingBar from "../../components/InterView/LoadingBar";
const ArticleManage = ({ navigation, route }) => {
  // const { type } = route.params;
  const { articleList, deleteArticle, isArticleLoading } =
    useContext(ArticleContext);

  const [isDelete, setIsDelete] = useState(false);
  const [deletedId, setDeletedId] = useState(null);

  React.useLayoutEffect(() => {
    // if (type == "deleteCard") {
    navigation.setOptions({
      headerRight: () => (
        <TouchableOpacity
          onPress={() => {
            setIsDelete((pre) => setIsDelete(!pre));
          }}
        >
          <AntDesign name="delete" size={22} color="#fff" />
        </TouchableOpacity>
      ),
    });
    // }
  }, [navigation]);

  const onConfirmeDeleted = (article) => {
    setDeletedId(article._id);
    Alert.alert("提示", "你确定要删除该文章吗?", [
      {
        text: "确定",
        onPress: () => {
          deleteArticle(article);
        },
      },
      {
        text: "取消",
      },
    ]);
  };

  return (
    <View style={styles.container}>
      {/* <Text>目前你还未发布任何文章</Text> */}
      <LoadingBar visible={isArticleLoading} />
      <FlatList
        ListEmptyComponent={<NoData />}
        data={articleList}
        keyExtractor={(item, index) => index.toString()}
        renderItem={({ item, index }) => {
          return (
            <ArticleCard
              article={item}
              type={0}
              isDelete={isDelete}
              onDeleted={onConfirmeDeleted}
              deletedId={deletedId}
              onPress={() => {
                navigation.navigate("ArticleDetail", {
                  article: item,
                });
              }}
            />
          );
        }}
      />
      <TouchableOpacity
        style={styles.Button}
        onPress={() => navigation.navigate("AddArticle")}
      >
        <Text style={styles.Text}>创建文章</Text>
      </TouchableOpacity>
    </View>
  );
};

var styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "white",
    // padding: 16,
  },
  Button: {
    borderRadius: 5,
    margin: 18,
    padding: 10,
    backgroundColor: "#3ABEF0",
    alignItems: "center",
    justifyContent: "center",
    elevation: 2, //设置阴影角度，通过这个设置有无阴影
    shadowColor: "gray", // 设置阴影色
  },
  Text: {
    fontSize: 16,
    color: "#fff",
    fontWeight: "bold",
  },
});

export default ArticleManage;
